package com.study.kafka;

import com.study.kafka.producer.Demo01Producer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.support.SendResult;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;

/**
 * @author yuantongqin
 * 2021/8/4
 **/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = KafkaApp.class)
public class Ta {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Demo01Producer producer;

    @Test
    public void sendSync(){
        Random random = new Random();
        Integer i = random.nextInt(100);
        try {
            SendResult sendResult = producer.syncSend(i);
            logger.info("[testSyncSend][发送编号：[{}] 发送结果：[{}]]", i, sendResult);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void sendAsync(){
        Random random = new Random();
        Integer i = random.nextInt(100);
        ListenableFuture<SendResult<Object, Object>> asyncSend = producer.asyncSend(i);
        asyncSend.addCallback(new ListenableFutureCallback<SendResult<Object, Object>>() {
            @Override
            public void onFailure(Throwable ex) {
                logger.error("失败",ex);
            }

            @Override
            public void onSuccess(SendResult<Object, Object> result) {

                logger.info("[testASyncSend][发送编号：[{}] 发送成功，结果为：[{}]]", i, result);
            }
        });

        CountDownLatch countDownLatch = new CountDownLatch(1);
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
